package cn.ymatrix.httpTOYMatrix;

import cn.ymatrix.logger.LoggerLevel;
import cn.ymatrix.logger.MxLogger;
import cn.ymatrix.utils.Config;
import cn.ymatrix.utils.DataUtil;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class HttpClientTOYMatrix {

  public static void main(String[] args) throws Exception {

    MxLogger.loggerLevel(LoggerLevel.INFO);
    Logger LOGGER = MxLogger.init(HttpClientTOYMatrix.class);

    int batchSize = Config.getBatchSize();
    int totalNumber = Config.getTotalNumber();
    String delimiter = Config.getDelimiter();
    String tableName = Config.getTableName();
    String url = Config.getHttpUrl();
    int insertCount = 0;
    int counter = 0;
    LOGGER.info("---- 开始插入数据 ----");
    StopWatch startWatch = StopWatch.createStarted();
    for (counter = 1; counter <= totalNumber; counter++) {
      if (counter % batchSize == 0) {
        insertCount++;
        HttpURLRequest(LOGGER, batchSize, url, tableName, delimiter);
        LOGGER.info("成功插入第 " + counter + " 条数据");
      }
    }
    int tailCount = totalNumber - insertCount * batchSize;
    if (tailCount != 0) {
      HttpURLRequest(LOGGER, tailCount, url, tableName, delimiter);
    }
    LOGGER.info(
        "成功插入 " + totalNumber + " 条数据,耗时: " + startWatch.getTime(TimeUnit.MILLISECONDS) + "毫秒");
  }

  private static void HttpURLRequest(
      Logger LOGGER, int batchSize, String url, String tableName, String delimiter)
      throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "text/plain");
    String postData = getPostData(batchSize, tableName, delimiter);
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.write(postData.getBytes(StandardCharsets.UTF_8));
    wr.flush();
    wr.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    int errorLineCount = 0;

    while ((inputLine = in.readLine()) != null) {
      // 检查行是否包含错误
      if (inputLine.contains("error")) {
        errorLineCount++;
        // 如果包含错误，输出错误行
        LOGGER.info("Error in line " + errorLineCount + ": " + inputLine);
      }
    }
    in.close();

    // 如果一批数据中有部分成功返回部分的报错信息
    // 如果一批数据全部出错，显示一批的报错信息
    if (500 == con.getResponseCode()) {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(con.getErrorStream(), StandardCharsets.UTF_8));
      String line = null;
      String result = "";
      while ((line = reader.readLine()) != null) {
        result += line;
      }
      reader.close();
      LOGGER.info("errorMsg: " + result);
    }
  }

  private static String getPostData(int batchSize, String tableName, String delimiter) {
    StringBuilder stringBuilder = new StringBuilder("public." + tableName + "\n");
    for (int i = 0; i < batchSize; i++) {
      stringBuilder.append(
          DataUtil.getCurrentTimestamp()
              + delimiter
              + DataUtil.getIntValue()
              + delimiter
              + DataUtil.getIntValue()
              + delimiter
              + DataUtil.getIntValue()
              + delimiter
              + DataUtil.getIntValue()
              + delimiter
              + DataUtil.getIntValue()
              + "\n");
    }
    return stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
  }
}
